#include "applicationscript.h"

#include <QtScript>
#include <QFile>
#include <QDir>

#include <optra/common/proxy.h>
#include <optra/appoptrainfo.h>
#include "optrzone.h"
O_Z

#define optra() OZ

extern Optra::Proxy* proxy;

ApplicationScript::ApplicationScript(const QString& name, QObject *parent) :
    Task(name, parent), appname_(name)
{
}


void ApplicationScript::run()
{    
    setCanRemove(false);
    emit state(QString("Initialize: %1").arg(appname_), Optra::LogEvent::debug);
    QDir d = proxy->directory(Optra::Proxy::applications);
    d.cd(appname_);


    Optra::AppOptraInfo ai;
    ai.setName(appname_);


    QScriptEngine engine;

    QScriptValue objectValue = engine.newQObject(this);
    QScriptValue mainZoneObject = engine.newQObject(optra());

    engine.globalObject().setProperty("main", objectValue);
    engine.globalObject().setProperty("optra", mainZoneObject);


    QFile file(d.absoluteFilePath(appname_) + ".oscript");
    file.open(QIODevice::ReadOnly);
    engine.evaluate(file.readAll(), "err.r");
}

QString ApplicationScript::test()
{
    return "";
}

void ApplicationScript::setTest(QString t)
{
    qDebug() << "Test Function:" << t;
}
